<script setup lang="ts">
import {ref,computed,watch} from "vue";
import loginTab from "@/components/user/login.vue"
import registryTab from "@/components/user/registry.vue"
import {useUserStore} from "@/stores/useUserStore.ts";
import {ElMessage,ElMessageBox} from "element-plus";
import {router} from "@/router/router";
import {onMounted} from "vue";
import request from "@/utils/request";

// 控制 APP 下载悬浮层（如果需要）
let showAppQr = ref(false);
let centerDialogVisible = ref(false);
let activeTab = ref('login');

// 关闭当前的登录窗口
function closeDialog(){
  centerDialogVisible.value = false;
}

// 获取用户状态
const userStore = useUserStore();

// 注销
function logout(){
  ElMessageBox.confirm('是否注销？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    userStore.$reset();
  })
}

//使用小说对象作为参数并打开新窗口跳转详情页（导航栏上只显示小说id和名字）
function goDetail(story) {
  window.open(router.resolve({path: '/details',query:{"story":JSON.stringify(story)}}).href)
}

//搜索框的内容初始化
const searchStory = ref('');
// 是否显示提示列表
const showSuggestList = ref(false);

//获取后端查询的数据
let storyList = ref([]);

// 计算属性：只返回前四项数据，跟随 storyList 变化
const displayStories = computed(() => {
  return storyList.value.slice(0, 4);
});

// 监听 searchStory 变化，输入时匹配数据并渲染提示列表，主动搜索
watch(searchStory, (newVal) => {
  const query = newVal.trim();
  if (query.length === 0) {
    showSuggestList.value = false;
    storyList.value = [];
    return;
  }
  // 向后端发起搜索请求
  request.get("/getNovelList", { params: { name: searchStory.value } })
      .then(response => {
        storyList.value = response.data;
        showSuggestList.value = true;
        console.log(storyList.value);
      })
      .catch(error => {
        ElMessage.error(error);
        showSuggestList.value = false;
        storyList.value = [];
      })
});


// // 4、输入时匹配数据并渲染提示列表,主动搜索
// const handleInput = () => {
//   const query = searchStory.value.trim();
//
//   // 判断是否显示提示列表
//   if  (query.length != 0){
//
//     showSuggestList.value = true; // 显示提示列表
//
//
//   } else {
//     showSuggestList.value = false; // 隐藏提示列表
//     storyList.value = []; // 重置为空数组
//   }
// };
//
// // 计算属性：只返回前四项数据
// const displayStories = storyList.value.slice(0, 4);


// 用户点击的导航（可根据实际路由需求完善跳转逻辑）
let chose = ref('home')
// 处理登录、注册、找回账号、找回密码等方法（可根据实际路由或逻辑完善）
function handleLogin() {
  centerDialogVisible.value = true;
  activeTab.value = 'login';
}
function handleRegister() {
  centerDialogVisible.value = true;
  activeTab.value = 'registry';
}
function handleFindAccount() {
  // 可补充找回账号逻辑，比如跳转到对应页面等
  ElMessage.info('找回账号功能待完善');
}
function handleFindPassword() {
  // 可补充找回密码逻辑，比如跳转到对应页面等
  ElMessage.info('找回密码功能待完善');

}

function gosy() {
  window.open(router.resolve({path: ''}).href)

}
function goYq() {
  router.push({path: '/yq'})
}
function goNoyq() {
  router.push({path: '/Noyq'})
}
function goNocp(){
  router.push({path: '/Nocp'})
}
function goYs(){
  router.push({path: '/ys'})
}
function goBh(){
  router.push({path: '/bh'})
}

function goPay(){
  window.open(router.resolve({path: '/pay'}).href)
}
</script>

<template>
  <!-- 顶部时间及登录注册栏 -->
  <div class="top-bar">
    <span class="time">
      北京时间 {{ new Date().getFullYear() }}年{{ new Date().getMonth() + 1 }}月{{ new Date().getDate() }}日 {{ new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) }}
    </span>
    <div class="top-links">
      <span class="link" @click="handleLogin" v-if="userStore.id==0">登入</span>
      <span class="link"  v-if="userStore.id!=0">欢迎:{{userStore.userName}}</span>
      <span class="link" @click="handleRegister" v-if="userStore.id==0">注册</span>
      <span class="link" @click="logout" v-if="userStore.id!=0">注销</span>
      <span class="link" @click="handleFindAccount" v-if="userStore.id==0">找回账号</span>
      <span class="link" @click="handleFindPassword" v-if="userStore.id==0">找回密码</span>
    </div>
  </div>

  <!-- 头部导航及logo区域 -->
  <div class="header">
    <div class="logo">
      <img src="@/assets/img/logo.png" alt="logo">
    </div>
    <div class="nav-categories">
      <div class="category" @click="goYq()">言情小说</div>
      <div class="category" @click="goNoyq()">纯爱小说</div>
      <div class="category" @click="goYs()">衍生/轻小说</div>
      <div class="category" @click="goNocp()">无CP小说</div>
      <div class="category" @click="goBh()">百合小说</div>
    </div>


    <!-- 搜索框，按照输入的文字找数据库内是否存在该小说，返回的形式是表单-->
    <div class="search-wrapper"> <!-- 新增外层容器，负责相对定位 -->
      <div class="search-bar">
        <input
            v-model="searchStory"
            placeholder="请输入内容搜索"
        />
      </div>
      <!-- 结果列表放到外层，基于.search-wrapper 定位 -->
      <div id="show-storyList" class="show-storyList" v-if="showSuggestList">
        <form >
          <ul>
            <li
                v-for="(story, index) in displayStories"
                :key="index"
                @click="goDetail(story)"
            >{{ story.name }}</li>
          </ul>
        </form>
      </div>
    </div>

    <div class="sub-nav">
      <div class="sub-link" @click="gosy()">首页</div>
      <div class="sub-link">完结文库</div>
      <div class="sub-link">出版影视</div>
      <div class="sub-link">小书喵悦读</div>
      <div class="sub-link">论坛</div>
      <div class="sub-link">繁体版</div>
      <div class="sub-link app-download" @mouseenter="showAppQr = true" @mouseleave="showAppQr = false">
        APP 下载
        <div class="app-qr" v-if="showAppQr">
          <img src="@/assets/img/app_qr.png" alt="APP 二维码">
        </div>
      </div>
    </div>
  </div>

  <!-- 主导航栏 -->
  <div class="main-nav">
    <div class="main-nav-item">作品库</div>
    <div class="main-nav-item">排行榜</div>
    <div class="main-nav-item">评论频道</div>
    <div class="main-nav-item">作者专区</div>
    <div class="main-nav-item">版权专区</div>
    <div class="main-nav-item">新闻活动</div>
    <div class="main-nav-item">征文活动</div>
    <div class="main-nav-item" @click="goPay()">充值</div>
    <div class="main-nav-item">求助投诉</div>
    <div class="main-nav-item" @click="handleLogin">注册/登入</div>
    <div class="main-nav-item">帮助</div>
    <div class="main-nav-item">娱乐</div>
  </div>

  <!-- 登录注册弹窗 -->
  <el-dialog v-model="centerDialogVisible" title="这是一个弹窗" width="20%" center>
    <template #header>
      <el-radio-group v-model="activeTab">
        <el-radio-button value="login">登录</el-radio-button>
        <el-radio-button value="registry">注册</el-radio-button>
      </el-radio-group>
    </template>
    <component @close-dialog="closeDialog" :is="activeTab==='login'?loginTab:registryTab"></component>
  </el-dialog>
</template>

<style scoped>
@import '@/assets/css/top.css';
</style>